package common.utils;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

/**
 * Created by yangkuo02 on 2017/6/2.
 */

public class UrlParser {

    public static String getProtocol(String urlStr) {
        URL url = initURL(urlStr);
        if (url == null) {
            return null;
        }
        return url.getProtocol();
    }

    public static int getPort(String urlStr) {
        URL url = initURL(urlStr);
        if (url == null) {
            return -1;
        }
        return url.getPort();
    }

    public static String getPath(String urlStr) {
        URL url = initURL(urlStr);
        if (url == null) {
            return null;
        }
        return url.getPath();
    }

    public static String getQuery(String urlStr) {
        URL url = initURL(urlStr);
        if (url == null) {
            return null;
        }
        return url.getQuery();
    }

    public static String getQuery(String urlStr, String key) {
        key += "=";
        String allQuery = getQuery(urlStr);
        if (allQuery == null || !allQuery.contains(key)) {
            return null;
        }
        String[] queries = allQuery.split("&");
        for (String query : queries) {
            if (query != null && query.contains(key)) {
                return query.replace(key, "");
            }
        }
        return null;
    }

    private static URL initURL(String urlStr) {
        if (urlStr == null || "".equals(urlStr)) {
            return null;
        }
        try {
            urlStr = URLDecoder.decode(urlStr, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            URL url = new URL(urlStr);
            return url;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
